package com.search.utils;

import org.apache.commons.beanutils.ConvertUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MapAndBean {
    /**
     * 将bean转为Map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> beanToMap(Object object) {
        Map<String, Object> result = new HashMap<>();

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String fieldName = propertyDescriptor.getName();
                if ("class".equals(fieldName)) {
                    continue;
                }

                Method readMethod = propertyDescriptor.getReadMethod();
                Object value = readMethod.invoke(object);

                result.put(fieldName, value);
            }


            return result;
        } catch (Exception e) {
            throw new RuntimeException("读取bean属性失败", e);
        }
    }

    public static <T> T mapToDomain(Map<String, Object> map, Class<T> tClass) {
        try {
            T t = tClass.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(tClass);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if ("class".equals(key)) {
                    continue;
                }
                if (map.containsKey(key)) {
                    try {
                        Object value = map.get(key);
                        // 得到property对应的setter方法
                        Method setter = property.getWriteMethod();
                        Class<?> type = property.getPropertyType();
                        // 强转为字段的类型，不需要时可以去除，依赖commons-beanutilss-beanutils
                        Object convert = ConvertUtils.convert(String.valueOf(value), type);
                        setter.invoke(t, convert);
                    } catch (Exception e) {
                        throw new RuntimeException("【赋值异常】", e);
                    }
                }
            }

            return t;
        } catch (Exception e) {
            throw new RuntimeException("【Map转换实体异常】", e);
        }
    }


}
